package com.prodog.utils.bean;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.prodog.utils.string.JSONUtils;
import org.springframework.beans.BeanUtils;

import java.util.LinkedHashMap;
import java.util.Map;

public class BeanUtil {
    public static Map<String, Object> beanToMap(Object obj) {
        return JSONUtils.parseObj(JSONUtils.toJSONString(obj), LinkedHashMap.class);
    }

    public static <T> T mapToBean(Map map, Class<T> clz) {
        return JSONUtils.parseObj(JSONUtils.toJSONString(map), clz);
    }

    public static <T> T beanToBean(Object obj, Class<T> clz) {
        return JSONUtils.parseObj(JSONUtils.toJSONString(obj), clz);
    }

    public static Map<String, Object> bean2Map(Object obj) {
        return JSONUtil.toBean(JSONUtil.toJsonStr(obj), LinkedHashMap.class);
    }

    public static <T> T map2Bean(Map map, Class<T> clz) {
        return JSONUtil.toBean(JSONUtil.toJsonStr(map), clz);
    }

    public static <T> T bean2Bean(Object obj, Class<T> clz) {
        return JSON.parseObject(JSON.toJSONString(obj), clz);
    }

    public static <T> T copy(Object obj, Class<T> clz) {
        Object res = ReflectUtil.newInstance(clz);
        BeanUtils.copyProperties(obj, res, clz);
        return (T) res;
    }
}
